package xyz.mumuwei.youthcourseserver.job;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import xyz.mumuwei.youthcourseserver.common.dto.TemplateData;
import xyz.mumuwei.youthcourseserver.common.dto.WechatMessageDto;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.mapper.CourseMapper;
import xyz.mumuwei.youthcourseserver.mapper.CourseTimeMapper;
import xyz.mumuwei.youthcourseserver.pojo.Course;
import xyz.mumuwei.youthcourseserver.pojo.CourseTime;
import xyz.mumuwei.youthcourseserver.service.WechatService;
import xyz.mumuwei.youthcourseserver.utils.TimeUtil;

import java.util.HashMap;

/**
 * 发送微信订阅消息
 * 课前提醒——用户预约课程
 * 课前发送微信消息提醒
 * @author mumuwei
 * @date 2022/4/16
 */
@Slf4j
@RequiredArgsConstructor
public class SendWechatReserveMessageJob extends QuartzJobBean {

    final WechatService wechatService;
    final CourseMapper courseMapper;
    final CourseTimeMapper timeMapper;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        JobDataMap dataMap = context.getMergedJobDataMap();
        WechatMessageDto wechatMessageDto = new WechatMessageDto();

        // 设置发送对象, 模板id
        wechatMessageDto.setTouser(dataMap.getString("openId"));
        wechatMessageDto.setTemplate_id(Const.CLASS_WECHAT_TEMPLATE_ID);

        // 获取课程id,进而获取课程信息
        int courseId = dataMap.getInt("courseId");
        Course course = courseMapper.selectById(courseId);

        // 构建消息数据
        HashMap<String, TemplateData> data = new HashMap<>(5);
        data.put("thing1", new TemplateData(course.getName()));

        // 判断是否体验课程消息
        int timeId = dataMap.getInt("timeId");
        if (timeId == 0) {
            // 体验课提醒
            data.put("date13", new TemplateData(TimeUtil.dateFormat(course.getExperienceTime(), "yyyy-MM-dd kk:mm")));
            data.put("thing6", new TemplateData("请提前到机构进行查看."));
            data.put("thing9", new TemplateData(("欢迎报名《" + course.getName() +"》课程。")));
        } else {
            // 学员正式课提醒
            CourseTime time = timeMapper.selectById(timeId);
            data.put("date13", new TemplateData(TimeUtil.dateFormat(time.getStartTime(), "yyyy-MM-dd kk:mm")));
            data.put("thing6", new TemplateData(time.getPlace()));
            data.put("thing9", new TemplateData("请按时参加课程。"));
        }

        wechatMessageDto.setData(data);
        // 发送消息
        JSONObject jsonObject = wechatService.subscribeMessageSend(wechatMessageDto);
        log.info("微信定时消息已发送,返回结果为:" + jsonObject.toString());
    }

}
